from flask import Blueprint, render_template, request, redirect, url_for, session, jsonify
from flask_login import login_user, logout_user, current_user
from app.models.user import User
from app.utils.db import db
import os

# 创建蓝图
auth_bp = Blueprint('auth', __name__)

# 登录页
@auth_bp.route('/login')
def login():
    if current_user.is_authenticated:
        return redirect(url_for('index.index'))
    return render_template('login.html')

# 登录接口
@auth_bp.route('/login_request', methods=['POST'])
def login_request():
    data = request.json
    username = data.get('username')
    password = data.get('password')

    # --- 数据库验证 ---
    session_db = db.get_session()
    user = session_db.query(User).filter_by(name=username).first()
    
    if user and user.password == password:  # 简单密码比较 (实际应用中应使用哈希)
        login_user(user)
        return jsonify({
            "success": True, 
            "message": "登录成功", 
            "redirect": url_for('index.index')
        })

    # --- 配置文件验证 (如果数据库中没有找到用户) ---
    # 从环境变量或配置获取默认用户
    default_username = os.environ.get('DEFAULT_USERNAME')
    default_password = os.environ.get('DEFAULT_PASSWORD')
    
    if username == default_username and password == default_password:
        # 创建默认用户
        default_user = User(
            name=username,
            password=password,
            is_admin=True
        )
        login_user(default_user)
        return jsonify({
            "success": True, 
            "message": "登录成功", 
            "redirect": url_for('index.index')
        })
    else:
        return jsonify({"success": False, "message": "用户名或密码错误"}), 401

# 登出接口
@auth_bp.route('/logout')
def logout():
    logout_user()
    return redirect(url_for('index.index')) 